
package com.bluelinelabs.conductor.conductor;

import ohos.aafwk.content.Intent;
import ohos.agp.components.ComponentContainer;
import ohos.app.AbilityContext;

import com.bluelinelabs.conductor.conductor.internal.LifecycleHandler;
import com.bluelinelabs.conductor.conductor.internal.TransactionIndexer;

import java.util.List;

/**
 * lipeiquan
 *
 * @since 2021-05-06
 */
public class ActivityHostedRouter extends Router {

    private LifecycleHandler lifecycleHandler;
    private final TransactionIndexer transactionIndexer = new TransactionIndexer();

    public final void setHost(LifecycleHandler lifecycleHandler, ComponentContainer container) {
        if (this.lifecycleHandler != lifecycleHandler || this.container != container) {
            if (this.container != null && this.container instanceof ControllerChangeHandler.ControllerChangeListener) {
                removeChangeListener((ControllerChangeHandler.ControllerChangeListener) this.container);
            }

            if (container instanceof ControllerChangeHandler.ControllerChangeListener) {
                addChangeListener((ControllerChangeHandler.ControllerChangeListener) container);
            }

            this.lifecycleHandler = lifecycleHandler;
            this.container = container;

            watchContainerAttach();
        }
    }


    @Override
    public AbilityContext getActivity() {

        return lifecycleHandler != null ? lifecycleHandler.getLifecycleActivity() : null;
    }

    @Override
    void registerForActivityResult(String instanceId, int requestCode) {
        lifecycleHandler.registerForActivityResult(instanceId, requestCode);
    }

    @Override
    TransactionIndexer getTransactionIndexer() {
        return transactionIndexer;
    }

    @Override
    List<Router> getSiblingRouters() {
        return lifecycleHandler.getRouters();
    }

    @Override
    void unregisterForActivityResults(String instanceId) {
        lifecycleHandler.unregisterForActivityResults(instanceId);
    }

    @Override
    boolean hasHost() {
        return lifecycleHandler != null;
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        lifecycleHandler.onActivityResult(requestCode, resultCode, data);
    }


    @Override
    void invalidateOptionsMenu() {
//        if (lifecycleHandler != null && lifecycleHandler.getFragmentManager() != null) {
//            lifecycleHandler.getFragmentManager().invalidateOptionsMenu();
//        }
    }

    @Override
    Router getRootRouter() {
        return this;
    }

    @Override
    public void onContextAvailable() {
        super.onContextAvailable();
    }

}
